//
//  YCTabBarController.swift
//  WeiboDemo
//
//  Created by 尹成 on 2017/1/6.
//  Copyright © 2017年 yc. All rights reserved.
//

import UIKit
import SVProgressHUD

class YCTabBarController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        setupNewFeature()
        
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(login), name: NSNotification.Name(rawValue: YCUserShouldLoginNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(register), name: NSNotification.Name(rawValue: YCUserShouldRegisterNotification), object: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    deinit {
        
        //销毁时钟
        timer?.invalidate()
        //销毁通知
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: - 私有控件
    //撰写按钮
    fileprivate lazy var composeButton:UIButton = UIButton()
    
    /// 有Timer 就要记得 在 deinit 中销毁
    fileprivate var timer:Timer?
}



/**
 extension 类似于OC中的分类,在Swift中还可以用来切分代码块
 可以将功能相近的函数,放在一个extension中
 便于维护代码
 注意:和oc的category一样,extension中不能定义属性
 */

//MARK: - 设置界面
extension YCTabBarController {
    
    func setupComposeButton() {
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        tabBar.addSubview(composeButton)
        let count = CGFloat( childViewControllers.count)
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * (tabBar.bounds.width / count), dy: 0)
        composeButton.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
    }
    
    
    /// portrait :竖屏,肖像     landscape:横屏,风景画
    /// 用代码控制设备方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    @objc private func composeButtonAction() {
        print("+++++++")
    }
    
    func setupChildControllers() -> (){
        
        //1.先从沙盒获取main.json，
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: jsonPath)
        //2.取不到则去bundle
        if data == nil || data!.length < 1{
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String:AnyObject]]
            else {
                return
        }
        
        viewControllers = setControllers(dictArray: array!)
        
    }
    
    private func setControllers(dictArray:[[String:AnyObject]]) -> [UIViewController] {
        
        var tempArray = [UIViewController]()
        
        for dict:Dictionary in dictArray {
            //1.获取字典内容
            guard let clsName = dict["clsName"] as? String,
                let title = dict["title"] as? String,
                let imageName = dict["imageName"] as? String,
                let selectimageName = dict["selectimageName"] as? String,
                let VC = NSClassFromString(Bundle.main.spaceName + "." + clsName) as? YCMainViewController.Type,
                let visitorDict = dict["visitorInfo"] as? [String:String]
                else {
                    tempArray.append(UIViewController())
                    continue
            }
            
            //2.创建试图控制器
            let vc = VC.init()
            
            //设置title
            vc.title = title
            
            //设置控制器的访客信息词典
            vc.visitorInfo = visitorDict
            
            //设置图片,选中图片,原图渲染
            vc.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal)
            vc.tabBarItem.selectedImage = UIImage(named: selectimageName)?.withRenderingMode(.alwaysOriginal)
            
            //设置标题,选中标题颜色
            //NSForegroundColorAttributeName,前景色
            vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.black], for:.selected)
            //系统默认 12 号字,可修改
            vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 11)], for: .normal)
            
            let nav = YCNavigationController(rootViewController: vc)
            tempArray.append(nav)
            
        }
        
        return tempArray
    }
}


// MARK: - 设置欢迎页
extension YCTabBarController{
    
    fileprivate func setupNewFeature(){
        
        let welecome = isFirstLuanch ? YCNewFeatureView.loadFromXib() : YCWelecomView.loadFromXib()
        view.addSubview(welecome)
    }
    
    private var isFirstLuanch:Bool{
        
        let localVersion = UserDefaults.standard.string(forKey: "AppVersion")
        
        let currentVersion:String = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        UserDefaults.standard.set(currentVersion, forKey: "AppVersion")

        return localVersion == currentVersion
    }
    
}


// MARK: - 时钟相关方法
extension YCTabBarController{
    
    fileprivate func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 500000.0,
                                     target: self,
                                     selector: #selector(timerAction),
                                     userInfo: nil,
                                     repeats: true)
    }
    
    @objc private func timerAction(){
        
        if !YCNetworkManager.shared.userLogon {
            return
        }
        
        //检查未读微博数量
        YCNetworkManager.shared.unreadCount { (count) in
            print("未读微博数量：",count)
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            // 设置app 的 badgeNumber ，从ios 8 开始，需要用户授权后 才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}


// MARK: - 处理tabbarItem的点击事件 (如果item 有 badgeNumber, 从其他item 切回该item时不做处理, 在该item 第二次点击时 处理badgeNumber)
extension YCTabBarController:UITabBarControllerDelegate{
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let index:Int = childViewControllers.index(of: viewController) ?? 0
        if selectedIndex == index && viewController.tabBarItem.badgeValue != nil{
            viewController.tabBarItem.badgeValue = nil
            let vc = ((viewController as! YCNavigationController).viewControllers[0] as! YCMainViewController)
            vc.tableView?.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
            
            // FIXME: 加载数据并刷新 与 滚动到最顶部方法 先后顺序需要手动处理
            /// 延迟加载,保证先滚动到最顶部 再 刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.2, execute: {
                vc.loadData()
            })
            
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
    
    // 使用👆方法 替换 👇 ,简化代码 2017年01月12日11:03:55
    
    //    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    //        if item.tag == 2 {
    //            return
    //        }
    //        dealBadgeNumber(item: item)
    //    }
    //
    //    private func dealBadgeNumber(item:UITabBarItem){
    //        print(item.tag)
    //
    //        if item.tag == lastSelectIndex {
    //            let vc:YCMainViewController = (childViewControllers[item.tag] as! YCNavigationController).viewControllers[0] as! YCMainViewController
    //            vc.tableView?.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
    //            vc.tableView?.scrollsToTop = true
    //            item.badgeValue = nil
    //        } else {
    //            lastSelectIndex = item.tag
    //        }
    //
    //    }
}

// MARK: - 处理通知
extension YCTabBarController{
    @objc fileprivate func login(n:Notification){
        
        var Time = DispatchTime.now()
        
        if n.object != nil {
            SVProgressHUD.showInfo(withStatus: "登录信息已过期，请重新登录")
            Time = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: Time) {
            let nv = UINavigationController(rootViewController: YCOAuthViewController())
            self.present(nv, animated: true, completion: nil)
        }
    
    }
        
    @objc fileprivate func register(){
        print("接收到 register 通知")
    }
}
